package cn.zhku.user.web.servlet;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.itcast.servlet.BaseServlet;
import cn.zhku.user.entity.UserEntity;
import cn.zhku.user.service.UserException;
import cn.zhku.user.service.UserService;

/**
 * Servlet implementation class UserServlet
 */
@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	UserService userService = new UserService();
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");//
		response.setContentType("text/html;charset=utf-8"); 
		ArrayList<UserEntity> userList = userService.query(); 
		request.setAttribute("userList", userList);
		request.getRequestDispatcher("list.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");//
		response.setContentType("text/html;charset=utf-8"); 
		
		String userId =  request.getParameter("userId");
		String userName =  request.getParameter("userName");
		String userPass =  request.getParameter("userPass");
		String age =  request.getParameter("age");
		String sex = request.getParameter("sex");
		String email = request.getParameter("email");
		
		try {
			UserEntity user = new UserEntity(Integer.parseInt(userId),userName,userPass,Integer.valueOf(age),sex,email);
			userService.edit(user);
		} catch (UserException e) {
			request.setAttribute("msg", e.getMessage());
			doGet( request, response);
		} 
		request.setAttribute("msg", "修改成功");
		doGet( request, response);	
	}
	
	

}
